package com.eian.boot.mybatis.core.page;

import com.eian.boot.common.core.utils.BeanCopierUtils;
import com.mybatisflex.core.paginate.Page;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.function.Function;

/**
 * @author alex.meng
 * @createTime 2025-09-04 15:16
 * @description 数据分页结果
 **/
@Data
@NoArgsConstructor
public final class PageResult<T> {

    private long total;

    private List<T> records;

    public PageResult(List<T> records, long total) {
        this.total = total;
        this.records = records;
    }

    public static <T> PageResult<T> build(Page<T> page) {
        PageResult<T> pageResult = new PageResult<>();
        pageResult.setTotal(page.getTotalRow());
        pageResult.setRecords(page.getRecords());
        return pageResult;
    }

    public static <T, R> PageResult<R> build(Page<T> page, Class<R> rClass) {
        PageResult<R> pageResult = new PageResult<>();
        pageResult.setTotal(page.getTotalRow());
        pageResult.setRecords(BeanCopierUtils.copyList(page.getRecords(), rClass));
        return pageResult;
    }

    public static <T> PageResult<T> build(List<T> records) {
        PageResult<T> pageResult = new PageResult<>();
        pageResult.setTotal(records.size());
        pageResult.setRecords(records);
        return pageResult;
    }

    public static <T> PageResult<T> build(List<T> records, long total) {
        PageResult<T> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setRecords(records);
        return pageResult;
    }

    public static <T, R> PageResult<R> build(Page<T> page, Function<T, R> function) {
        PageResult<R> pageResult = new PageResult<>();
        pageResult.setTotal(page.getTotalRow());
        pageResult.setRecords(page.getRecords().stream().map(function).toList());
        return pageResult;
    }

    /**
     * 构建表格分页数据对象
     */
    public static <T> PageResult<T> build() {
        return new PageResult<>();
    }
}
